package io.fatmore.web.interceptor;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

public class ApiRequestWrapper extends HttpServletRequestWrapper {

	private final String body;

	public ApiRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
		body = stringBuilder.toString();
	}

	/*public ApiRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		List<Byte> bytes = new ArrayList<>();
		BufferedReader bufferedReader = null;
		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				int contentLength = request.getContentLength();
        		*//*当无请求参数时，request.getContentLength()返回-1 *//*
				if(contentLength<0){
					body = "";
					return;
				}
				byte buffer[] = new byte[contentLength];
				for (int i = 0; i < contentLength;) {

					int readlen = request.getInputStream().read(buffer, i,
							contentLength - i);
					if (readlen == -1) {
						break;
					}
					i += readlen;
				}

				byte[] decryptBytes = EnDecryptor.decrypt(buffer);
				body = decryptBytes.toString();
			} else {
				body = "";
			}
		} catch (IOException ex) {
			throw ex;
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
		}
	}*/
	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
		ServletInputStream servletInputStream = new ServletInputStream() {
			@Override
			public boolean isFinished() {
				return byteArrayInputStream.available() == 0;
			}

			@Override
			public boolean isReady() {
				return true;
			}

			@Override
			public void setReadListener(ReadListener readListener) {

			}

			public int read() throws IOException {
				return byteArrayInputStream.read();
			}


		};
		return servletInputStream;
	}

	@Override
	public BufferedReader getReader() throws IOException {
		return new BufferedReader(new InputStreamReader(this.getInputStream()));
	}

	public String getBody() {
		return this.body;
	}
}
